<template>
    <div>
        <el-card>
            <template #header>
                <div>
                    <el-form :model="formData" ref="form" label-width="80px" :inline="false">
                        <el-row :gutter="20">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="选择计划">
                                    <el-input style="width: 350px; margin-right: 10px;"
                                        v-model="formData.productionPlanId" placeholder="请选择计划" disabled></el-input>
                                    <el-button type="primary" @click="showPlanModal">选择计划</el-button>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" :offset="0">
                                <el-form-item label="选择任务">
                                    <el-input style="width: 350px; margin-right: 10px;" v-model="formData.taskId"
                                        placeholder="请选择任务" disabled></el-input>
                                    <el-button type="primary" @click="showTaskModal">选择任务</el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="8" :offset="0">
                                <el-form-item label="产品编号" prop="materialId">
                                    <el-input style="width: 350px;" disabled placeholder="请输入产品编号"
                                        v-model="formData.materialId"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label="产品名称" prop="materialName">
                                    <el-input style="width: 350px;" disabled placeholder="请输入产品名称"
                                        v-model="formData.materialName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label="产品单位" prop="unit">
                                    <el-input style="width: 350px;" disabled placeholder="请输入产品单位"
                                        v-model="formData.unit"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="24">
                            <el-col :span="24" :offset="0">
                                <el-form-item label="规格型号" prop="specificationsAndModels">
                                    <el-input style="width: 350px;" type="textarea"
                                        v-model="formData.specificationsAndModels"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="8" :offset="0">
                                <el-form-item label="报工数量" prop="totalQuantity">
                                    <el-input style="width: 350px;" type="number" placeholder="请输入报工数量"
                                        v-model="formData.totalQuantity" disabled>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label="合格数量" prop="qualifiedQuantity">
                                    <el-input style="width: 350px;" type="number" placeholder="请输入报工数量"
                                        v-model="formData.qualifiedQuantity" @input="updateTotalQuantity"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label="不合格数量" prop="defectQuantity">
                                    <el-input style="width: 350px;" type="number" placeholder="请输入报工数量"
                                        v-model="formData.defectQuantity" @input="updateTotalQuantity"></el-input>
                                </el-form-item>
                            </el-col>

                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="8" :offset="0">
                                <el-form-item label="报工日期" prop="reportTime">
                                    <el-date-picker style="width: 350px;" type="datetime" placeholder="请选择报工日期"
                                        v-model="formData.reportTime"
                                        value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label="报工人员" prop="reportId">
                                    <template #default>
                                        <el-select v-model="formData.reportId" placeholder="请选择报工人员">
                                            <el-option v-for="item in users" :key="item.username" :label="item.nickname" :value="item.username"/>
                                        </el-select>
                                    </template>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label="质检员" prop="checkId">
                                    <template #default>
                                        <el-select v-model="formData.checkId" placeholder="请输入质检员">
                                            <el-option v-for="item in users" :key="item.username" :label="item.nickname" :value="item.username"/>
                                        </el-select>
                                    </template>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-form-item>
                            <el-button type="primary" @click="submitForm" v-if="formData.status === 0">保存</el-button>
                            <el-button @click="submitApproval" v-if="formData.status === 0">
                                提交审批
                            </el-button>
                            <el-button type="primary" @click="cancelForm" v-if="formData.status !== 0">返回</el-button>
                            <el-button @click="Yes" v-if="formData.status === 1">审批通过</el-button>
                            <el-button @click="No" v-if="formData.status === 1">审批不通过</el-button>
                            <el-button @click="cancelForm">取消</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <el-dialog v-model="orderDialogVisible" title="选择计划" width="70%">
                <el-table :data="plans" style="width: 100%;">
                    <el-table-column label="计划编号" prop="planId" width="120" />
                    <el-table-column label="计划名称" prop="planName" width="120" />
                    <el-table-column label="产品编号" prop="materialId" width="120" />
                    <el-table-column label="产品名称" prop="materialName" width="120" />
                    <el-table-column label="规格型号" prop="specificationsAndModels" width="120" />
                    <el-table-column label="单位" prop="unit" width="120" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button @click="selectPlan(scope.row)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-dialog>

            <el-dialog v-model="taskDialogVisible" title="选择任务" width="70%">
                <el-table :data="taskData" border style="width: 100%">
                    <el-table-column prop="taskId" label="任务编号" width="150" />
                    <el-table-column prop="taskName" label="任务名称" width="150" />
                    <el-table-column prop="workstationId" label="工作站编号" width="150" />
                    <el-table-column prop="workstationName" label="工作站名称" width="150" />
                    <el-table-column prop="taskQuantity" label="排产数量" width="150" />
                    <el-table-column prop="computedQuantity" label="已生产数量" width="150" />
                    <el-table-column prop="startDate" label="开始时间" width="150" />
                    <el-table-column prop="endDate" label="预计完成时间" width="150" />
                    <el-table-column label="操作" right-align>
                        <template #default="scope">
                            <el-button @click="selectTask(scope.row)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-dialog>
            <!-- card body -->
        </el-card>


    </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue'
import request from '@/api/request'
import { useRouter } from 'vue-router'

const users = ref([])
onMounted(async()=>{
    request.post('/system/user/list',{size:1000}).then(res => {
        users.value = res.data.records})
})


let props = defineProps(["data"])

let emits = defineEmits(['ref-table'])

console.log(props.data)

// 监听合格数量和不合格数量的变化，自动更新总数量
const updateTotalQuantity = () => {
    const qualified = parseFloat(formData.value.qualifiedQuantity) || 0
    const defect = parseFloat(formData.value.defectQuantity) || 0
    formData.value.totalQuantity = qualified + defect
}


// 保存表单
let submitForm = async () => {
    let data = {
        reportId: formData.value.reportId,
        productionPlanId: formData.value.productionPlanId,
        taskId: formData.value.taskId,
        reportPeopleId: formData.value.reportPeopleId,
        totalQuantity: formData.value.totalQuantity,
        qualifiedQuantity: formData.value.qualifiedQuantity,
        defectQuantity: formData.value.defectQuantity,
        reportTime: formData.value.reportTime,
        checkId: formData.value.checkId,
    }
    request({
        url: 'report/updateReport',
        method: 'put',
        data: data,
    }).then(res => {
        console.log(res)
        //提交表单
        if (res.data == true) {
            //弹窗提示
            alert("保存成功")
            //刷新表单
            emits("ref-table")
        }
    })

}

let cancelForm = () => {
    //取消表单
    emits("ref-table")
}

//审批相关
let submitApproval = async () => {
    //提交审批
    // 先保存数据
    await submitForm()

    // 然后更新状态为待审批（假设1是待审批状态）
    const approvalData = {
        ...formData.value,
        status: 1 // 更新状态为待审批
    }

    request({
        url: '/report/updateReport', // 确认这个接口路径是否正确
        method: 'put',
        data: approvalData,
    }).then(res => {
        if (res.data == true) {
            ElMessage.success('提交审批成功')
            formData.value.status = 1
            emits('ref-table')
        }
    })
}
let Yes = async () => {
    //审批通过

    // 校验报工数量
    if (!validateReportQuantity()) {
        return
    }
    // 确认审批
    await ElMessageBox.confirm(
        `确定要通过审批吗？报工数量：${formData.value.totalQuantity}，将更新任务已生产数量。`,
        '审批确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )

    // 先保存数据
    await submitForm()

    // 更新任务已生产数量
    const updateSuccess = await updateTaskComputedQuantity(formData.value.totalQuantity)
    console.log('更新任务数量结果:', updateSuccess)
    // if (!updateSuccess) {
    //     ElMessage.error('更新任务数量失败')
    //     return
    // }

    // 然后更新状态为已审批（假设2是已审批状态）
    const approvalData = {
        ...formData.value,
        status: 2 // 更新状态为已审批
    }

    request({
        url: '/report/updateReport', // 确认这个接口路径是否正确
        method: 'put',
        data: approvalData,
    }).then(res => {
        if (res.data == true) {
            ElMessage.success('审批通过')
            formData.value.status = 2

            // 更新本地选中的任务数据
            if (selectedTask.value) {
                selectedTask.value.computedQuantity += formData.value.totalQuantity
            }
            emits('ref-table')
        }
    })
}
let No = async () => {
    //审批不通过
    // 先保存数据
    await submitForm()
    // 然后更新状态为未确认（假设0是未确认状态）
    const approvalData = {
        ...formData.value,
        status: 0 // 更新状态为未确认
    }

    request({
        url: '/report/updateReport', // 确认这个接口路径是否正确
        method: 'put',
        data: approvalData,
    }).then(res => {
        if (res.data == true) {
            ElMessage.success('审批不通过')
            formData.value.status = 0
            emits('ref-table')
        }
    })
}
let formData = ref({ ...props.data })//表单数据

let orderDialogVisible = ref(false)//计划弹窗是否显示
let taskDialogVisible = ref(false)//任务弹窗是否显示



let plans = ref([])//计划列表

let showPlanModal = () => {
    orderDialogVisible.value = true
    request({
        url: 'report/planAll',
        method: 'get',
    }).then(res => {
        plans.value = res.data
    })
}//显示计划弹窗

let selectPlan = async (plan) => {
    //选择计划
    formData.value.productionPlanId = plan.planId
    formData.value.materialId = plan.materialId
    formData.value.materialName = plan.materialName
    formData.value.specificationsAndModels = plan.specificationsAndModels
    formData.value.unit = plan.unit
    orderDialogVisible.value = false

}


//任务数据
let taskData = ref([])

let showTaskModal = () => {
    taskDialogVisible.value = true
    request({
        url: '/report/taskAll',
        method: 'GET',
    }).then(res => {
        taskData.value = res.data
    })
}//显示任务弹窗

// 选中的任务信息
let selectedTask = ref(null)

let selectTask = async (task) => {
    // 选择任务
    formData.value.taskId = task.taskId
    selectedTask.value = { ...task } // 保存选中的任务信息
    console.log(selectedTask.value)
    taskDialogVisible.value = false

    // 显示提示信息
    const remaining = task.taskQuantity - task.computedQuantity
    ElMessage.info(`当前任务剩余数量：${remaining}`)
}



// 校验报工数量是否超过剩余数量
const validateReportQuantity = () => {
    console.log(selectedTask.value)
    if (!selectedTask.value) {
        ElMessage.warning("请先选择任务")
        return false
    }

    const taskQuantity = selectedTask.value.taskQuantity
    const computedQuantity = selectedTask.value.computedQuantity
    const reportQuantity = formData.value.totalQuantity
    const remainingQuantity = taskQuantity - computedQuantity

    if (reportQuantity > remainingQuantity) {
        ElMessage.error(`报工数量(${reportQuantity})超过剩余数量(${remainingQuantity})`)
        return false
    }

    return true
}

// 更新任务的已生产数量
const updateTaskComputedQuantity = async (additionalQuantity) => {
    if (!selectedTask.value) return false
        const updateData = {
            taskId: selectedTask.value.taskId,
            computedQuantity: selectedTask.value.computedQuantity + additionalQuantity
        }

        const response = await request({
            url: '/report/task/updateComputedQuantity', // 假设有这个接口
            method: 'put',
            data: updateData
        })

        return response.data === true
}

// 初始化选中的任务
const initSelectedTask = async (taskId) => {
    if (!taskId) return
    // 从任务列表中查找对应的任务
    const response = await request({
        url: '/report/taskAll',
        method: 'GET',
    })

    if (response.data) {
        const task = response.data.find(t => t.taskId === taskId)
        if (task) {
            selectedTask.value = { ...task }
            console.log('初始化选中的任务:', selectedTask.value)
        } else {
            console.warn('未找到对应的任务数据，taskId:', taskId)
        }
    }
}

// 监听props.data的变化，初始化formData和selectedTask
watch(() => props.data, (newVal) => {
    console.log('props.data发生变化:', newVal)
    formData.value = { ...formData.value, ...newVal }

    // 如果存在taskId，则初始化selectedTask
    if (newVal && newVal.taskId) {
        initSelectedTask(newVal.taskId)
    }
}, { immediate: true, deep: true })



// 组件挂载时初始化任务数据
onMounted(() => {
    if (formData.value.taskId) {
        initSelectedTask(formData.value.taskId)
    }
})

</script>

<style scoped></style>
